package com.tt.vtg.dao.entity;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name="T_ROLE")
public class Role extends AbstractEntity {
	private static final long serialVersionUID = 7041802037240639737L;

	@Column(name="ROLENAME")
	private String roleName;
	
	@Column(name="ROLEID")
	private String roleId;
	
	// lazy fetch by default 
	@ManyToMany(fetch=FetchType.EAGER)
	@JoinTable(name="T_ROLE_PERM",
				joinColumns=@JoinColumn(name="role_pk"),
				inverseJoinColumns=@JoinColumn(name="perm_pk", updatable=false))
	@JsonIgnore
	private Set<Permission> permissions = new HashSet<Permission>();
	
	@ManyToMany(mappedBy="roles")
	@JsonIgnore
	private Set<User> users = new HashSet<>();

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	
	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}
	
	public void addPermissions(Permission... perms) {
		permissions.addAll(Arrays.asList(perms));
	}
	
	public void removePermission(Permission... perms){
		permissions.removeAll(Arrays.asList(perms));
	}
	
	public void addPermissions(Permission perm) {
		permissions.add(perm);
	}
	
	public void removePermission(Permission perm){
		permissions.remove(perm);
	}
	
	public Set<Permission> getPermissions() {
		return permissions;
	}

	public void setPermissions(Set<Permission> permissions) {
		this.permissions = permissions;
	}

	public Set<User> getUsers() {
		return users;
	}

	public void addUsers(User... us) {
		Arrays.asList(us).forEach(u -> users.add(u));
	}
}
